package LC;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * https://leetcode.com/problems/subsets-ii/description/
 * Given a collection of integers that might contain duplicates, nums, return all possible subsets.
 * Note: The solution set must not contain duplicate subsets.
 * For example,
 * If nums = [1,2,2], a solution is:
 * [
 * [2],
 * [1],
 * [1,2,2],
 * [2,2],
 * [1,2],
 * []
 * ]
 */
public class LC_090_SubsetsII_DFS_BackTracking_Recur {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 3};
        List<List<Integer>> res = Solution.subsetsWithDup(a);
        System.out.println(res.toString());
    }

    static class Solution {
        static List<List<Integer>> subsetsWithDup(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            if (nums == null || nums.length < 1)
                return res;
            Arrays.sort(nums);
            ArrayList<Integer> list = new ArrayList<>();
            dfs(nums, 0, res, list);
            return res;
        }

        private static void dfs(int[] nums, int start, List<List<Integer>> res, ArrayList<Integer> list) {
            res.add(new ArrayList<>(list));
            if (start >= nums.length)
                return;
            for (int i = start; i < nums.length; i++) {
                if (i > start && nums[i] == nums[i - 1])
                    continue;
                list.add(nums[i]);
                dfs(nums, i + 1, res, list);
                list.remove(list.size() - 1);
            }
        }

    }
}
